package com.zhanghe.im.handler;

import com.zhanghe.im.protocol.command.PacketCodeC;
import com.zhanghe.im.request.MessageRequestPacket;
import com.zhanghe.im.response.MessageResponsePacket;
import com.zhanghe.im.session.Session;
import com.zhanghe.im.util.SessionUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * SimpleMessageRequestHandler
 *
 * @author Clevo
 * @date 2018/10/23
 */
public class SimpleMessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageRequestPacket messageRequestPacket) throws Exception {
        // 1.拿到消息发送方的会话信息
        Session session = SessionUtil.getSession(channelHandlerContext.channel());

        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFormUserId(session.getUserId());
        messageResponsePacket.setFormUserName(session.getUserName());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());

        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());
        if(toUserChannel!=null && SessionUtil.hasLogin(toUserChannel)){
            toUserChannel.writeAndFlush(messageResponsePacket);
            System.err.println("发送消息[" + messageRequestPacket.getMessage() + "] 给用户["+messageRequestPacket.getToUserId()+"]!");
        }else{
            System.err.println("[" + messageRequestPacket.getToUserId() + "] 不在线，发送失败!");
        }
    }

}
